<template>
  <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload">
    <img v-if="imageUrl" :src="imageUrl" class="w-[30px] h-[30px] rounded-full" />
    <img src="@/assets/images/avatar.jpg" alt="" v-else class="w-[30px] h-[30px] rounded-full" />
  </el-upload>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'

import type { UploadProps } from 'element-plus'
import { uploadFile } from '@/apis/auth'
import { URL } from 'url'

const imageUrl = ref('')
const props = defineProps<{
  modelValue?: string
}>()
watch(
  () => props.modelValue,
  (newVal) => {
    imageUrl.value = newVal!
  },
  {
    immediate: true,
  }
)
const emit = defineEmits<{
  (e: 'update:modelValue', val: string): void
  (e: 'finish'): Promise<void>
}>()
const upload = async (options: any) => {
  console.log(options)
  imageUrl.value = window.URL.createObjectURL(options.file)
  // emit('update:modelValue', imageUrl.value)
  // emit('finish')
  // const formData = new FormData()
  // formData.append('file', options.file)
  // const res = await uploadFile(formData)
  // if (res.code !== 200) return
  // imageUrl.value = res.data.url.startsWith('http') ? res.data.url : `http://${res.data.url}`
  // emit('update:modelValue', imageUrl.value)
  // emit('finish')
  // console.log()
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>

<style scoped lang="scss">
.avatar-uploader {
  display: flex;
  justify-content: center;
}
</style>
